'use strict'

const { ApiController } = require('jax')

class Controller extends ApiController {
  get Model() {
    return this.ctx.model.AdminOrganize
  }

  // 查询前
  async beforeIndex() {
    const { ctx } = this
    const { query, helper } = ctx
    const { admin } = ctx.state

    const filter = {
      // 所属系统
      systemType: admin.systemType,
    }

    // 模糊查询
    const search = ['organizeName']
    for (let key of search) {
      if (query[key]) filter[key] = new RegExp(helper.toMongoRegex(query[key]), 'i')
    }

    ;['systemType', 'sourceId'].map((key) => {
      if (query[key] && !query[key] == '') filter[key] = query[key]
    })

    // 非管理员系统
    if (admin.systemType != 'admin') {
      filter.sourceId = admin.sourceId
    }
    return {
      filter,
    }
  }

  // 树
  async tree() {
    const { ctx } = this

    const filter = this.getFilter()

    const tree = await this.Model.tree({
      filter: filter,
      sort: {
        isTop: 'DESC',
        rank: 'ASC',
      },
    })

    // await this.recurseTree(tree, async (categoryItem) => {
    //   await this.formatData(categoryItem)
    // })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: tree,
    }
  }

  // 新增前
  async beforeCreate() {
    const { ctx } = this
    const { body } = ctx.request
    const { admin } = ctx.state

    body.systemType = admin.systemType // 所属系统
  }

  // 格式化
  async formatData(organize) {
    const { ctx } = this

    // 关联当前部门的用户数
    // organize.userNum = await ctx.model.Admin.count({ organizeId: organize.organizeId })
  }

  // 删除前
  async beforeDestroy() {
    const { ctx } = this
    const { params } = ctx

    // 判断部门是否绑定了子部门
    const res = await ctx.model.AdminOrganize.find({ parentId: params.id })
    if (res.length != 0) throw '该部门绑定了子部门，不能删除'
  }

  // 保存后
  async afterSave(doc) {
    if (doc.parentId) {
      const parent = await this.Model.findOne({ _id: doc.parentId })
      doc.chainId = parent.chainId
      doc.chainIds = [...parent.chainIds, doc._id]
    } else {
      doc.chainId = doc._id
      doc.chainIds = [doc._id]
    }

    doc.save()
  }
}

module.exports = Controller
